import { useMemo } from 'react'
import styles from './index.module.scss'
import chunk from 'lodash-es/chunk'
import { useState } from 'react'
import { useSportWindowWidth } from '@/utils/hooks'
import cm from 'classnames'
import Link from 'next/link'
import { SPORT_INFO } from '@/constant'

const urlObj = SPORT_INFO.reduce((final, target) => {
  final[target.name] = target.url
  return final
}, {})
const Index = props => {
  const { count } = useSportWindowWidth()
  const { data } = props
  const dataArr = useMemo(() => {
    return chunk(data, count)
  }, [data, count])
  const [current, setCurrent] = useState(0)

  const next = e => {
    e.stopPropagation()
    current <= dataArr.length && setCurrent(current + 1)
  }
  const prev = e => {
    e.stopPropagation()
    current && setCurrent(current - 1)
  }

  if (!data || !data.length) return null

  const preventDefaults = e => {
    e.stopPropagation()
  }

  return (
    <div
      className={cm(styles.items, {
        [styles.itemsLeft]: dataArr[current].length < count
      })}
    >
      {current !== 0 ? (
        <img
          loading="lazy"
          alt="切换"
          src="/images/arrow.png"
          className={cm(styles.arrow, styles.arrowLeft, 'hideWhenPhone')}
          onClick={prev}
        />
      ) : null}
      {dataArr[current].map((item, index) => {
        return (
          <div key={index} className={cm(styles.item, 'hideWhenPhone')} style={{ width: `calc(100% / ${count})` }}>
            <Link onClick={preventDefaults} href={'/sports/' + urlObj[item.name]} className={styles.img}>
              <img loading="lazy" src={item.icon} alt={item.name} />
            </Link>
            <p className={styles.name}>{item.name}</p>
          </div>
        )
      })}
      {current !== dataArr.length - 1 && dataArr.length > 1 ? (
        <img
          loading="lazy"
          alt="切换"
          src="/images/arrow.png"
          className={cm(styles.arrow, styles.arrowRight, 'hideWhenPhone')}
          style={{ transform: 'rotate(180deg)' }}
          onClick={next}
        />
      ) : null}
      {data.map((item, index) => {
        return (
          <div key={index} className={cm(styles.itemPhone, 'hideWhenPc')}>
            {item[0]}
          </div>
        )
      })}
    </div>
  )
}

export default Index
